#include "command.h"

int _head(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 4) {
		fprintf(stderr, "Usage: head [-n num] file\n");
		return -1;
	}

	int lines_to_read = 10; 
	int opt; 		/* option character */
	const char *opt_fmt = "n:"; /* option format */

	/* parse the cmd-line parameters */
	while ((opt = getopt(argc, argv, opt_fmt)) != -1) {
		switch (opt) {
			case 'n': 
				lines_to_read = atoi(optarg);
				break;
			default:
				fprintf(stderr, "Usage: head [-n num] file\n");
				return -1;
		}
	}

	/* handle wrong case about lines_to_read */
	if (lines_to_read <= 0) {
		fprintf(stderr, "Option error: -n num--->num must be greater than 0\n");
		return -1;
	}

	if (!argv[optind]) {
		fprintf(stderr, "Usage: head [-n num] file\n");
		return -1;
	}

	const char *file = argv[optind];
	int fd;
    // If a file is provided, open it; otherwise, use stdin
    if (file) {
        fd = open(file, O_RDONLY);
        if (fd == -1) {
            fprintf(stderr, "head error: open\n");
            return -1;
        }
    } else {
        fd = STDIN_FILENO; // Use standard input
    }

	/* read the content to buffer and write to stdout */
	lseek(fd, 0, SEEK_SET);
	int line_count = 0;
	int num_read = 0;
	char buf[BUF_SIZE];

	while ((num_read = read(fd, buf, BUF_SIZE)) > 0) {
		for (int i = 0; i < num_read; i++) {
			write(STDOUT_FILENO, &buf[i], 1);
			if (buf[i] == '\n') {
				line_count++;
				if (line_count == lines_to_read) {
					if (fd != STDIN_FILENO)
						close(fd);
					return 0;
				}
			}
		}
	}
	if (fd != STDIN_FILENO)
		close(fd);

	if (num_read == -1) {
		fprintf(stderr, "head error: read\n");
		return -1;
	}

	return 0;
}
